package org.apache.catalina.startup;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.util.Objects;
import org.apache.tomcat.util.buf.UriUtil;
import org.apache.tomcat.util.file.ConfigurationSource;

/**
 * CatalinaBaseConfigurationSource
 *
 * @author chentudong
 * @date 2024/2/19 15:42
 * @since 1.0
 */
public class CatalinaBaseConfigurationSource implements ConfigurationSource {

  private final String serverXmlPath;
  private final File catalinaBaseFile;
  private final URI catalinaBaseUri;

  public CatalinaBaseConfigurationSource(File catalinaBaseFile, String serverXmlPath) {
    this.serverXmlPath = serverXmlPath;
    this.catalinaBaseFile = catalinaBaseFile;
    this.catalinaBaseUri = catalinaBaseFile.toURI();
  }

  @Override
  public Resource getResource(String name) throws IOException {
    if (!UriUtil.isAbsoluteURI(name)) {
      File file = new File(name);
      if (!file.isAbsolute()) {
        file = new File(catalinaBaseFile, name);
      }
      if (file.isFile()) {
        return new Resource(Files.newInputStream(file.toPath()), file.toURI());
      }
    }
    return null;
  }

  /**
   * getServerXml
   *
   * @return Resource
   * @throws IOException IOException
   */
  @Override
  public Resource getServerXml() throws IOException {
    IOException ioe = null;
    Resource result = null;
    try {
      if (Objects.isNull(serverXmlPath) || serverXmlPath.equals(Catalina.SERVER_XML)) {
        result = ConfigurationSource.super.getServerXml();
      } else {
        result = getResource(serverXmlPath);
      }
    } catch (IOException e) {
      ioe = e;
    }
    if (Objects.isNull(result) && Objects.nonNull(ioe)) {
      throw ioe;
    } else {
      return result;
    }
  }
}
